package com.itheima.health.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.health.common.MessageConst;
import com.itheima.health.dao.PermissionDao;
import com.itheima.health.dao.RoleDao;
import com.itheima.health.dao.UserDao;
import com.itheima.health.entity.PageResult;
import com.itheima.health.entity.QueryPageBean;
import com.itheima.health.entity.Result;
import com.itheima.health.pojo.Permission;
import com.itheima.health.pojo.Role;
import com.itheima.health.pojo.User;
import com.itheima.health.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author zhangmeng
 * @description 用户服务实现类
 * @date 2019/9/6
 **/
@Slf4j
@Service
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;



    @Override
    public User findByUsername(String username) {
        User user = userDao.selectByUsername(username);
        return user;
    }

    /**
     * 用户管理分页查询
     * @param queryPageBean
     * @return
     */
    @Override
    public PageResult findpage(QueryPageBean queryPageBean) {

        PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());
        Page<User> page = userDao.selectfindpage(queryPageBean.getQueryString());
        return new PageResult(page.getTotal(),page.getResult());
    }

    /**
     * 新增用户
     * @param user
     */
    @Override
    public void add(User user, Integer[] roleIds) {
        log.info("[用户-新增]data:{},rolrIds:{}",user,roleIds);
        userDao.insert(user);
        for (Integer roleId : roleIds) {
            userDao.insertUserAndRole(user.getId(),roleId);
        }
    }

    /**
     * 根据id删除
     * @param id
     */
    @Override
    public void delete(Integer id) {
        userDao.deleteAssociation(id);
        userDao.deleteuser(id);
    }

    /**
     * 根据id查询信息
     * @param id
     */
    @Override
    public User findById(Integer id) {
        User user =  userDao.selectfindByid(id);
        return user;
    }

    /**
     * 编辑
     * @param user
     * @param
     */
    @Override
    public void edit(User user,Integer[] roleIds) {
        userDao.updateedit(user);
        userDao.deleteAssociation(user.getId());
        System.out.println(roleIds);
        //给用户添加对应的角色
        for (Integer roleId : roleIds) {
            userDao.insertUserAndRole(user.getId(),roleId);
        }
    }


    @Override
    public List<Integer> findRoleIdsByUserId(Integer id) {
        return userDao.findRoleIdsByUserId(id);
    }

}
